package club.gskj.gulimall.ware.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import club.gskj.common.exception.BizCodeEnume;
import club.gskj.common.exception.NoStockException;
import club.gskj.gulimall.ware.vo.SkuHasStockVo;
import club.gskj.gulimall.ware.vo.WareSkuLockVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import club.gskj.gulimall.ware.entity.WareSkuEntity;
import club.gskj.gulimall.ware.service.WareSkuService;
import club.gskj.common.utils.PageUtils;
import club.gskj.common.utils.R;


/**
 * 商品库存
 *
 * @author 康纳-connor
 * @email 2417039231@gmail.com
 * @date 2021-02-07 10:08:31
 */
@RestController
@RequestMapping("ware/waresku")
public class WareSkuController {

    @Autowired
    private WareSkuService wareSkuService;

    /***
     *  订单锁定库存
     * @return
     */
    @PostMapping("/order/lock")
    public R orderLockStock(@RequestBody WareSkuLockVo wareSkuLockVo) {
        try {
            Boolean aBoolean = wareSkuService.orderLockStock(wareSkuLockVo);
            // 为扑捉到 NoStockException异常，说明库存锁定成功
            return R.ok().setData(aBoolean);
        } catch (NoStockException e) {
            e.printStackTrace();
            return R.error(BizCodeEnume.NO_STOCK_EXCEPTION.getCode(), BizCodeEnume.NO_STOCK_EXCEPTION.getMsg()).setData(e.getSkuId());
        }
    }

    /**
     * @param skuIds
     * @return club.gskj.common.utils.R
     * @author 康纳-connor
     * @creed: Talk is cheap,show me the code
     * @date 21.2.10 17:19
     * @Description 查询 sku是否保存库存
     */
    @PostMapping("/hasstock")
    public R hasStockBySku(@RequestBody List<Long> skuIds) {
        // sku_id
        // stock
        List<SkuHasStockVo> list = wareSkuService.hasStock(skuIds);

        //R<List<SkuHasStockVo>> ok = R.ok();
        //ok.setData(list);
        return R.ok().setData(list);
    }


    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = wareSkuService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id) {
        WareSkuEntity wareSku = wareSkuService.getById(id);

        return R.ok().put("wareSku", wareSku);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody WareSkuEntity wareSku) {
        wareSkuService.save(wareSku);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody WareSkuEntity wareSku) {
        wareSkuService.updateById(wareSku);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids) {
        wareSkuService.removeByIds(Arrays.asList(ids));
        return R.ok();
    }
}
